#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import re
from bible.TheHolyBible import *
from email.charset import Charset
from google.appengine.api import urlfetch

# urls = ["http://www.holybible.or.kr/B_GAE/", "http://www.holybible.or.kr/B_AGAPE/"]
# urls = ["http://www.holybible.or.kr/B_GAE/"]
urls = {'GAE':"http://www.holybible.or.kr/B_GAE/", 'RHV':"http://www.holybible.or.kr/B_RHV/", 'COGNEW':"http://www.holybible.or.kr/B_COGNEW/", 'SAE':"http://www.holybible.or.kr/B_SAE/", 'AGAPE':"http://www.holybible.or.kr/B_AGAPE/", 'DURANNO':"http://www.holybible.or.kr/B_DURANNO/", 'NIV':"http://www.holybible.or.kr/B_NIV/"}

def fetchUrl(self, url):
    try:
        result = urlfetch.fetch(url)
        if result.status_code != 200:
            self.response.out.write('Result : %s<br />%s' % (result.status_code, 'Network error'))
            self.response.out.write("%s" % result.content)
            return None
    except:
        self.response.out.write('Result : %s' % ('Network error'))
        return None

    return result.content


def getBooks(self, code):
    url = urls[code]
    content = fetchUrl(self, url)
    if content == None:
        return

    book_list = {};
    c = Charset()
    c.input_codec = "euc-kr"
    c.output_codec = "utf-8"
    for m in re.finditer(r"\<td class=tk3\>\<li\><a href=\".*VL=([0-9]{1,2}).*\"\>(.*)\</a\>\</td\>", content):
        code = (int)(m.group(1))
        name = m.group(2)
        book_list[code] = c.convert(name)

    books = [];
    for i in range(len(book_list)):
        book = BibleBook(i+1, book_list[i+1])
        books.append(book)
    return books


def getVerses(self, biblename, booknum, chapternum):

    if biblename == "": biblename = "GAE"
    if booknum == "": booknum = "1"
    if chapternum == "": chapternum = "1"

    url = "http://www.holybible.or.kr/B_" + biblename + "/cgi/bibleftxt.php?VR=" + biblename + "&VL=" + str(booknum) + "&CN=" + str(chapternum) + "&CV=99&FR="

    c = Charset()
    c.input_codec = "euc-kr"
    c.output_codec = "utf8"

    content = fetchUrl(self, url)
    lines = []
    try:
        for m in re.finditer(r"\<li\>\<font class=tk4l\>(.*)\</font\>", content):
            line = m.group(1)
            lines.append(c.convert(re.sub(r'<[^>]*?>', '', line)))
    except:
        pass

    return lines


def getBookUrls(self):
    for url in urls:
        content = fetchUrl(self, url)
        if content == None:
            continue

        books = {};
        for m in re.finditer(r"\<td class=tk3\>\<li\><a href=\"(.*)\"\>(.*)\</a\>\</td\>", content):
            url = m.group(1)
            book = m.group(2)

        for k, v in books.iteritems():
            self.response.out.write("%s %s<br/>" % (k, v))
